<script lang="ts" setup>
import { ref, watch, nextTick, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

import { useClassID } from '@/composables/useClassID'
import { LabID } from '@/constants/lab'

import { getRouteLocationByLabID } from '../router'
import type { DebuggerInfo } from './types'

defineEmits<{ run: [] }>()
const props = defineProps<{ debuggerInfo: DebuggerInfo }>()
const logStyle = {
  WARN: 'text-orange',
  SUCCESS: 'text-arco-success-6',
  INFO: 'text-blue-5',
  ERROR: 'text-red'
}
const { t } = useI18n<[typeof import('./locales/zh-CN.json')]>({ useScope: 'parent' })

const logger = ref<HTMLDivElement>()
watch(props.debuggerInfo, () => {
  nextTick(() => (logger.value!.scrollTop = (logger.value?.scrollHeight ?? 0) + 10))
})

const isSuccess = computed(() => props.debuggerInfo.slice(-1)[0]?.[0] === 'SUCCESS')

const classID = useClassID()
const router = useRouter()
const gotoSimulation = async () => {
  await router.push(getRouteLocationByLabID(LabID.MIMOSimulator, classID.value))
}
</script>

<template>
  <div class="flex flex-col overflow-hidden">
    <div class="flex items-center">
      <a-button-group type="dashed" size="small">
        <a-button @click="$emit('run')" status="success">
          <i class="i-mdi-play text-xl" /><span class="ml-1 font-bold">{{
            t('console.startTest')
          }}</span>
        </a-button>
        <a-button
          @click="gotoSimulation"
          :disabled="!isSuccess"
          :status="isSuccess ? 'success' : 'warning'"
        >
          <i class="i-mdi-label-variant text-xl" /><span class="ml-1 text-bold">
            {{ t('console.simulation') }}
          </span>
        </a-button>
      </a-button-group>
    </div>
    <div ref="logger" class="overflow-auto flex-1 scrollbar-slim scrollbar:bg-arco-2">
      <p v-for="[type, log] of debuggerInfo" :key="log" class="ma-1">
        <span class="font-bold select-none" :class="logStyle[type]" v-text="`${type}:`"></span>
        <span class="font-bold ml-2">{{ log }}</span>
      </p>
    </div>
  </div>
</template>
